const jwt = require("jsonwebtoken");

const secretKey = "irelib";
const signOptions = {
  expiresIn: "12h",
};
const verifyOptions = {};

const useJwt = {
  sign: (payload, secret = secretKey, options = signOptions) => {
    return jwt.sign(payload, secret, options);
  },
  verify: (token, secret = secretKey, options = verifyOptions) => {
    let verify = false;
    jwt.verify(token, secret, options, (err, decoded) => {
      verify = !err;
      if (err) {
        verify = false;
      } else {
        verify = decoded;
      }
    });
    return verify;
  },
};

// 验证token
function verifyRouter(req, res, next) {
  const verify = useJwt.verify(
    req.headers?.authorization?.replace("Bearer ", ""),
  );
  if (verify) {
    next();
  } else {
    res.status(401).send({
      message: "Token已过期",
    });
  }
}

module.exports = {
  useJwt,
  verifyRouter,
};
